import CryptoJS from '@r/common/crypto-js';
import JSEncrypt from '@r/common/jsencrypt.min.js';
import config from '@r/config';
import randomString from './randomString';

export default class Crypt {
  iv;
  key;
  publicKey;

  constructor() {
    this.publicKey = config.crypto.publicKey;
    this.iv =randomString(16);
    this.key =randomString(32);
  }

  aes_encrypt(text) {
    if (text) {
      try {
        const encoded = CryptoJS.AES.encrypt(
          text,
          CryptoJS.enc.Utf8.parse(this.key),
          {
            iv: CryptoJS.enc.Utf8.parse(this.iv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
          }
        );
        return encoded.toString();
      } catch (err) {
        return err;
      }
    }
    return '';
  }

  aes_decrypt = (text) => {
    if (text) {
      try {
        const decode = CryptoJS.AES.decrypt(
          text,
          CryptoJS.enc.Utf8.parse(this.key),
          {
            iv: CryptoJS.enc.Utf8.parse(this.iv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
          }
        );
        return decode.toString(CryptoJS.enc.Utf8);
      } catch (err) {
        return err;
      }
    }
    return '';
  };

  rsa_key_encrypt = () => {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(this.publicKey);
    return encrypt.encrypt(JSON.stringify({ iv: this.iv, key: this.key })); // 把Key进行非对称加密
  };
}
